import type { FC } from 'react';
import type Konva from 'konva';
import { Text } from 'react-konva';
import { useMemoizedFn, useSafeState } from 'ahooks';
import { useMemo, memo, useRef, useEffect } from 'react';

type Size = {
  width: number;
  height: number;
}

type CenterTextProps = {
  text?: string;
  size: number;
  fontSize?: number;
  fill?: string;
}

const CenterText: FC<CenterTextProps> = (props) => {
  const { size, text, fontSize } = props;
  const ref = useRef<Konva.Text>(null);
  const [textSize, setTextSize] = useSafeState<Size>();

  const x = useMemo(() => {
    const width = textSize?.width || 0;
    return (size - width) / 2;
  }, [textSize]);

  const y = useMemo(() => {
    const height = textSize?.height || 0;
    return (size - height) / 2;
  }, [textSize]);

  const onLayout = useMemoizedFn(() => {
    const text = ref.current;
    if (text) setTextSize(text.getClientRect());
  });

  useEffect(onLayout, [size, text, fontSize]);

  return (
    <Text
      x={x}
      y={y}
      ref={ref}
      align="center"
      text={props.text}
      fill={props.fill}
      fontSize={props.fontSize}
    />
  );
}

export default memo(CenterText);